package cn.itcast.controller;

import cn.itcast.config.WXPayExample;
import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.service.WebSocketServer;
import cn.itcast.utils.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayWxPay {

    @Autowired
    private WXPayExample wxPayExample;

    @Autowired
    private WebSocketServer webSocketServer;

    @GetMapping("/wxPay")
    public Result payWxPay() throws Exception {
        //获取付款码的url对象
        String url = wxPayExample.indentUrl();
        System.out.println("PayWxPay:");
        System.out.println(url);
        return new Result(true, MessageConstant.ORDER_SUCCESS, url);
    }

    @RequestMapping("/statu")
    public String verify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取流信息
        System.out.println("执行流方法");
        InputStream inputStream = request.getInputStream();
        //转换类型
        System.out.println("执行类型转换");
        String s = ConvertUtils.convertToString(inputStream);
        //验证交易信息
        System.out.println("执行验证信息");
        Map<String, String> map = WXPayUtil.xmlToMap(s);


        //设置交易成功信息
        map.put("return_code","SUCCESS");
        //设置给微信端的值
        String toXml = WXPayUtil.mapToXml(map);
        //利用WebSocket返回交易成功信息,跳转页面
        System.out.println("交互前端");
        webSocketServer.onMessage("SUCCESS");
        //返回微信端成功
        return toXml;
    }
}
